package com.alibaba.nacos.client.logging.logback;

import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.action.ActionUtil;
import ch.qos.logback.core.joran.spi.SaxEventInterpretationContext;
import ch.qos.logback.core.util.OptionHelper;
import com.alibaba.nacos.client.env.NacosClientProperties;
import org.xml.sax.Attributes;

public class NacosClientPropertyAction extends Action {

    private static final String DEFAULT_VALUE_ATTRIBUTE = "defaultValue";

    private static final String SOURCE_ATTRIBUTE = "source";

    @Override
    public void begin(SaxEventInterpretationContext intercon, String name, Attributes attributes) {
        String key = attributes.getValue(NAME_ATTRIBUTE);
        String source = attributes.getValue(SOURCE_ATTRIBUTE);
        ActionUtil.Scope scope = ActionUtil.stringToScope(attributes.getValue(SCOPE_ATTRIBUTE));
        String defaultValue = attributes.getValue(DEFAULT_VALUE_ATTRIBUTE);
        if (OptionHelper.isNullOrEmpty(name)) {
            addError("The \"name\" and \"source\"  attributes of <nacosClientProperty> must be set");
        }

        if (scope != ActionUtil.Scope.CONTEXT) {
            addError("the \"scope\"  attributes of <nacosClientProperty> not support");
            return;
        }

        String value = getValue(source, defaultValue);
        addInfo("add key: " + value + " value: " + value);
        intercon.getContext().putProperty(key, value);
    }

    @Override
    public void end(SaxEventInterpretationContext intercon, String name) {

    }

    private String getValue(String source, String defaultValue) {
        return NacosClientProperties.PROTOTYPE.getProperty(source, defaultValue);
    }

}
